<template>
  <el-drawer v-model="isShow" direction="rtl" :size="550">
    <template #header>
      <span>{{ title }}</span>
    </template>
    <template #default>
      <SchemaForm
        ref="schemaFormRef"
        v-loading="loading"
        :schema="components[name]?.schema"
        @update-form-field="onUpdateFormFiled"
      />
    </template>
    <template #footer>
      <el-button @click="close"> 取消 </el-button>
      <el-button type="primary" @click="save">
        {{ saveBtnText }}
      </el-button>
    </template>
  </el-drawer>
</template>

<script setup>
import { ref, inject } from "vue";
import SchemaForm from "$aegisWidgets/schema-form/schema-form.vue";
import $curl from "$aegisCommon/curl";
import { ElNotification } from "element-plus";
const { api, components } = inject("schemaViewData");
const emit = defineEmits(["command"]);
const name = ref("createForm");

const isShow = ref(false);
const title = ref("");
const saveBtnText = ref("");
const show = () => {
  const { config } = components.value[name.value];
  title.value = config.title;
  saveBtnText.value = config.saveBtnText;
  isShow.value = true;
};
const close = () => {
  isShow.value = false;
  //清空数据
  schemaFormRef.value.reset();
};
const schemaFormRef = ref();
const loading = ref(false);
const save = async () => {
  if (loading.value) return;
  // 校验
  if (!schemaFormRef.value.validate()) {
    return;
  }
  loading.value = true;
  const res = await $curl({
    url: api.value,
    method: "post",
    data: { ...schemaFormRef.value.getValue() },
  });
  loading.value = false;
  if (!res || !res.success) {
    return;
  }
  ElNotification.success({
    title: "成功",
    message: "创建成功",
  });
  close();
  // 刷新表格数据
  emit("command", {
    event: "loadTableData",
  });
};
defineExpose({
  name,
  show,
});
/**
 * 处理联动规则
 * @param {linkages} linkages 联动规则
 * @param {currentValue} currentValue 字段值
 */
const onUpdateFormFiled = ({ linkages, currentValue }) => {
  linkages.forEach((linkage) => {
    // 检查条件
    if (!linkage.condition) {
      return;
    }
    let conditionFn = null;
    try {
      conditionFn = new Function("return " + linkage.condition)();
    } catch (error) {
      console.error(linkage.condition + `函数表达式错误`);
    }
    if (!conditionFn) {
      return;
    }
    if (conditionFn && !conditionFn(currentValue, { ...schemaFormRef.value.getValue() })) {
      return;
    }

    // 处理目标字段（支持多目标）
    const targetFields = Array.isArray(linkage.target) ? linkage.target : [linkage.target];

    targetFields.forEach((targetName) => {
      const targetField = components.value[name.value]?.schema.properties[targetName];
      if (!targetField) return;

      // 执行联动动作
      switch (linkage.action) {
        case "show":
          targetField.option.visible = true;
          break;
        case "hide":
          targetField.option.visible = false;
          break;
        case "enable":
          targetField.option.disabled = false;
          break;
        case "disable":
          targetField.option.disabled = true;
          break;
        case "updateOptions":
          if (typeof linkage.options === "string") {
            try {
              const optionsFn = new Function("return " + linkage.options)();
              targetField.option.emunList = optionsFn(targetName, { ...schemaFormRef.value.getValue() });
            } catch (error) {}
          } else {
            targetField.option.emunList = linkage.options;
          }
          break;
        case "custom":
          linkage.customAction?.(targetField, { ...schemaFormRef.value.getValue() });
          break;
        default:
      }
    });
  });
};
</script>

<style scoped lang="less"></style>
